package com.example.thread.day12ReentrantLock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * ReentrantLock锁申请等待限时
 */
public class Demo2 {
    private static ReentrantLock lock = new ReentrantLock();

    public static class T extends Thread {
        public T(String name) {
            super(name);
        }

        @Override
        public void run() {
            try {
                System.out.println(System.currentTimeMillis() + ":" + this.getName() + "开始获取锁");
//                if (lock.tryLock()) {//tryLock() 返回Boolean值，是否获取到了锁
                if (lock.tryLock(3, TimeUnit.SECONDS)) {//3秒内是否获取到了锁
                    System.out.println(System.currentTimeMillis() + ":" + this.getName() + "获取到了锁");
                    TimeUnit.SECONDS.sleep(5);
                } else
                    System.out.println(System.currentTimeMillis() + ":" + this.getName() + "没有获取到锁");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                if (lock.isHeldByCurrentThread())
                    lock.unlock();
            }
        }

        public static void main(String[] args) {
            T t1 = new T("t1");
            T t2 = new T("t2");

            t1.start();
            t2.start();
        }
    }
}
